package com.auxgroup.hr.front.service.hireperson.impl;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.auxgroup.hr.front.commons.BaseRetCode;
import com.auxgroup.hr.front.commons.config.BusinessConfig;
import com.auxgroup.hr.front.commons.exception.FrontException;
import com.auxgroup.hr.front.commons.utils.DateUtils;
import com.auxgroup.hr.front.commons.utils.File2Byte;
import com.auxgroup.hr.front.commons.utils.FtpFileUtil;
import com.auxgroup.hr.front.dao.domain.PsCHireFileTbl;
import com.auxgroup.hr.front.dao.domain.PsChireFilePrimary;
import com.auxgroup.hr.front.dao.repository.PsCHireFileTblRepository;
import com.auxgroup.hr.front.service.hireperson.HireFileService;

/** 
 * @author lvliuhao
 * @version 创建时间：180523 
 * 入职人员文件内容service
 */
@Service("hireFileService")
public class HireFileServiceImpl implements HireFileService {
	private static final Logger logger = LoggerFactory.getLogger(HireEducatServiceImpl.class);
	
	@Autowired
	private PsCHireFileTblRepository PsCHireFileTblRepository;
	
	@Value("${auxgroup.hr.ftp.filepath}")
	private  String FTP_BASEPATH;//图片路径
	
	@Autowired
	private FtpFileUtil ftpUtil;
	
	@Autowired
	private BusinessConfig businessConfig;


	@Override
	public PsCHireFileTbl getHireFile(PsChireFilePrimary filePrimary) {
		return PsCHireFileTblRepository.findOne(filePrimary);
	}


	@Override
	public PsCHireFileTbl save(String rshireId,String base64, PsCHireFileTbl HireFile) {
		try {
			HireFile.setHrsRowAddOprid(rshireId);
			HireFile.setHrsRowAddDttm(new Timestamp(System.currentTimeMillis()));
			HireFile.setHrsRowUpdOprid(rshireId);
			HireFile.setHrsRowUpdDttm(new Timestamp(System.currentTimeMillis()));
			StringBuilder ftpFileName = new StringBuilder(DateUtils.getCurrentDateAsString(DateUtils.FORMAT_YYYYMMDDHHMISSSSS));
			String suffix = File2Byte.getImgSuffixFromBase64(base64);
			ftpFileName.append(HireFile.getRsHireId());
			ftpFileName.append(".");
			ftpFileName.append(suffix);
			//上传附件
			byte[] imgByte = File2Byte.base64ToImgByte(base64, businessConfig.getEmplePhotoResourceLocation());

			String ftpPath = getFtpPath(HireFile);
			Boolean isSucc = ftpUtil.uploadFile(ftpPath,ftpFileName.toString(), new ByteArrayInputStream(imgByte));
			if(!isSucc){
				throw new FrontException(BaseRetCode.CODE_ERROR_HIREFILE_UPLOAD_FAILED);
			}
			HireFile.setAttachsysfilename(ftpFileName.toString());
			HireFile.setFilePath(ftpPath);
			BigDecimal maxSeqno = PsCHireFileTblRepository.getMaxSeqNo(rshireId, HireFile.getcFileNum());
			if(maxSeqno==null){
				HireFile.setSeqno(new BigDecimal(1));
			}else{
				HireFile.setSeqno(maxSeqno.add(new BigDecimal(1)));
			}
			HireFile = PsCHireFileTblRepository.save(HireFile);
		} catch (Exception e) {
			logger.error("get file inputstream failed：",e);
			throw new FrontException(BaseRetCode.CODE_ERROR_HIREFILE_UPLOAD_FAILED);
		}
		return HireFile;
	}


	@Override
	public Boolean delete(PsChireFilePrimary filePrimary) {
		try {
			PsCHireFileTblRepository.delete(filePrimary);
		} catch (Exception e) {
			logger.error("delete HireFile error: filePrimary={}",filePrimary,e);
			return false;
		}
		return true;
	}
	
	
	@Override
	public List<PsCHireFileTbl> getAll(String rsHireId,String fileNum) {
		PsCHireFileTbl HireFile = new PsCHireFileTbl();
		HireFile.setRsHireId(rsHireId);
		HireFile.setcFileNum(fileNum);
		return PsCHireFileTblRepository.findAll(Example.of(HireFile));
	}

	/**
	 * 获取ftp文件路径
	 * @param HireFile
	 * @return
	 */
	public String getFtpPath(PsCHireFileTbl HireFile){
		StringBuilder filePath = new StringBuilder(FTP_BASEPATH);
		if(HireFile.getHrsRowAddDttm()!=null){
			filePath.append(DateUtils.format(new Date(HireFile.getHrsRowAddDttm().getTime()), DateUtils.FORMAT_YYYY));
		}else{
			filePath.append(DateUtils.format(new Date(), DateUtils.FORMAT_YYYY));
		}
		filePath.append("/");
		filePath.append(HireFile.getcFileNum());
		filePath.append("/");
		return filePath.toString();
	}
	
	
	
}
